package iscript.gameFramework.GameLite.graphics.animation 
{
	import flash.geom.Point;
	import flash.geom.Rectangle;
	import iscript.gameFramework.GameLite.events.BitmapBatchEvent;
	import iscript.gameFramework.GameLite.Game;

	public class BitmapBatchManager 
	{
		private var _bitmapBatchList:Vector.<BitmapBatch>
		public function BitmapBatchManager() 
		{
			_bitmapBatchList = new Vector.<BitmapBatch>();
		}
		
		public function add(bitmapbatch:BitmapBatch):void {
			   if(_bitmapBatchList.indexOf(bitmapbatch)==-1){
			      _bitmapBatchList.push(bitmapbatch);
			      bitmapbatch.addEventListener(BitmapBatchEvent.DISPOSE,_bbDispose)
			   }
			}
			
		private function _bbDispose(e:BitmapBatchEvent):void 
		{
			var bitmapbatch:BitmapBatch =  BitmapBatch(e.target);
			bitmapbatch.removeEventListener(BitmapBatchEvent.DISPOSE, _bbDispose);
			remove(bitmapbatch);
		}
			
		public function remove(bitmapbatch:BitmapBatch):void {
			var index:int =  _bitmapBatchList.indexOf(bitmapbatch);
			if (index != -1) {
				_bitmapBatchList.splice(index, 1);
				}
		}
		
		public function get count():int { return _bitmapBatchList.length; }
		
		/**
		 * 优化显示位图,不在范围的不现实
		 */
		public function optimize(rectview:Rectangle=null):void {
			    //INFO:如果不包含在Stage中,自动隐藏。
				for each (var item:BitmapBatch in _bitmapBatchList){
				if(item.IsinStage && !item.Disposed){
					var rect:Rectangle = rectview==null? new Rectangle(0, 0,
													   Game.graphicsDeviceManager.stage.stageWidth,
													   Game.graphicsDeviceManager.stage.stageHeight):rectview;;
					var point:Point =  Game.graphicsDeviceManager.toDevicePoint(item)
					var thisViewRect:Rectangle = new Rectangle(point.x, point.y, item.width, item.height);				
					item.visible = rect.intersects(thisViewRect);
				}
			}
		}
	}

}